import os

from django.conf import settings
from django.shortcuts import render
from django.template import loader
from django.utils import timezone

from .models import NewsChannel, Article
from django.core.paginator import Paginator, EmptyPage

def static_index_html():
    """
    将新闻首页实现页面静态化处理
    """
    channels = NewsChannel.objects.order_by('id')

    # 获取NewsChannel对象
    newsChannel = NewsChannel.objects.get(id=1)

    # 获取当前频道下的所有类别
    categories_id_list = [news_category.id for news_category in newsChannel.newscategory_set.all() if news_category]

    # 查询当前频道下的所有文章
    articles = Article.objects.filter(category_id__in=categories_id_list).order_by('id')

    # 分⻚
    # 创建分⻚器：每⻚N条记录
    paginator = Paginator(articles, 3)
    # 获取第一页的数据
    page_articles = paginator.page(1)

    # 准备页面数据
    context =  {'articles': page_articles, 'channel_id':1,'channels':channels}

    # 获取⾸⻚模板⽂件
    template = loader.get_template('newsapp/index.html')
    # 渲染⾸⻚html字符串
    html_text = template.render(context)
    # 将⾸⻚html字符串写⼊到指定⽬录，命名'index.html'
    file_path = os.path.join(settings.STATICFILES_DIRS[0],'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)
    print(timezone.localtime().strftime('%H:%M:%S'))
